import thin_render from "../../../lib/thin_render.mjs";
import { thin } from "../../../thin3.mjs";

/**
 * 渲染删除/插入按钮
 * @param {Object} params - 渲染参数
 */
export function renderDeleteButton({ tr, template, mode, insert }) {
  if ((template.rowinsert || template.rowdelete) && mode === "edit") {
    let td = document.createElement("td");
    tr.appendChild(td);

    if (insert && template.rowinsert) {
      // 渲染插入按钮
      thin_render(td, {
        button: "insert",
        click: (e) => {
          if (typeof template.rowinsert === "function") {
            template.rowinsert(e, () => handleInsert(tr, template, e));
          } else if (template.rowinsert === true) {
            handleInsert(tr, template, e);
          }
        },
      });
    } else if (!insert && template.rowdelete) {
      // 渲染删除按钮
      thin_render(td, {
        button: "delete",
        click: (e) => {
          if (typeof template.rowdelete === "function") {
            template.rowdelete(e, () => handleDelete(tr, template, e));
          } else if (template.rowdelete === true) {
            handleDelete(tr, template, e);
          }
        },
      });
    }
  }
}

function handleDelete(tr, template, e) {
  let tbody = tr.closest("tbody");
  let d = tbody.thin_rowdata;
  d.splice(tr.rowindex, 1);
  thin(tbody).empty();
  template.rerender(tbody, d);
  template?.deleted?.(e);
}

function handleInsert(tr, template, e) {
  let tbody = tr.closest("tbody");
  let d = tbody.thin_rowdata;

  // 收集新行数据
  let newData = { ...tr.thin_data };
  let inputs = tr.querySelectorAll("input,select,textarea");
  inputs.forEach((input) => {
    if (input.name) {
      newData[input.name] = input.value;
    }
  });

  // 添加新行到数据中
  d.push(newData);

  // 清空并重新渲染
  thin(tbody).empty();
  template.rerender(tbody, d);
  template?.inserted?.(e);
}
